package com.liruo.learn.spring.mvc.config.mvc;

import com.lowagie.text.Table;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class ViewResolverConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.viewResolver(new ResourceBundleViewResolver());
    }

    @Bean
    public View pdfView() {
        return new AbstractPdfView() {
            @Override
            protected void buildPdfDocument(Map<String, Object> model, com.lowagie.text.Document document, com.lowagie.text.pdf.PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
                Map<String, Integer> revenueData = (Map<String, Integer>) model.get("user");
                //columns=2, 不用管第二个参数，反正是2列，每一次addCell都会加1个单元格，2列就是2个单元格满，每2个就是一行
                Table table = new Table(2);
                table.addCell("name");
                table.addCell("age");

                for (Map.Entry<String, Integer> entry : revenueData.entrySet()) {
                    table.addCell(entry.getKey());
                    table.addCell(entry.getValue() + "");
                }
                document.add(table);
            }
        };
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        //配置ContentNegotiationManager, 好像没什么用
        configurer
                .favorParameter(false)
                .ignoreAcceptHeader(false)
                //加strategies
                .defaultContentType(MediaType.APPLICATION_JSON, MediaType.APPLICATION_PDF)
                //加extension
                .mediaType("pdf", MediaType.APPLICATION_PDF)
                .mediaType("json", MediaType.APPLICATION_JSON);
    }

//        @Bean
//        public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
//            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
//            resolver.setContentNegotiationManager(manager);
//            List<ViewResolver> resolvers = new ArrayList<>();
//            resolver.setViewResolvers(resolvers);
//            return resolver;
//        }
}